<template>
  <div class="news-page">
    <!-- 页面标题 -->
    <header class="page-header">
      <h1 class="page-title">新闻资讯</h1>
    </header>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-else-if="errorMessage" class="error-message">
      <i class="iconfont icon-error"></i>
      <p>{{ errorMessage }}</p>
    </div>
    
    <!-- 新闻列表 -->
    <div v-else class="news-list">
      <div 
        v-for="(item, index) in newsList" 
        :key="item.title || index" 
        class="news-item"
        @click="goToDetail(item.url)"
      >
        <!-- 新闻图片 -->
        <div class="news-image">
          <img 
            v-if="item.pic" 
            :src="item.pic" 
            alt="news image" 
            class="image-item"
            @error="handleImageError(index)"
          >
          <div v-else class="no-image">暂无图片</div>
        </div>
        
        <!-- 新闻内容 -->
        <div class="news-content">
          <h3 class="news-title">{{ item.title || '无标题' }}</h3>
          <p class="news-desc" v-if="item.content">
            {{ truncateContent(item.content) }}
          </p>
          
          <!-- 新闻元信息 -->
          <div class="news-meta">
            <span class="source">{{ item.src || '未知来源' }}</span>
            <span class="time">{{ formatTime(item.time) }}</span>
            <span class="category">{{ item.category || '' }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页控件 -->
    <div v-if="newsList.length > 0 && hasMore" class="pagination" @click="loadMore">
      加载更多
    </div>
    
    <!-- 空数据状态 -->
    <div v-if="!loading && !errorMessage && newsList.length === 0" class="empty-state">
      <i class="iconfont icon-empty"></i>
      <p>暂无新闻数据</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    // 响应式数据
    const newsList = ref([]);
    const loading = ref(true);
    const errorMessage = ref('');
    const currentPage = ref(1);
    const hasMore = ref(true);
    const isLoadingMore = ref(false);
    
    // 获取新闻数据
    async function fetchNewsData(page = 1) {
      try {
        loading.value = true;
        isLoadingMore.value = page > 1;
        
        // 修改接口地址
        const response = await fetch(`http://10.92.19.1:5000/news?page=${page}&limit=10`);
        
        // 处理网络错误
        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('API响应数据:', data);
        
        // 解析API数据结构
        if (data.status === 0 && data.result && Array.isArray(data.result.list)) {
          const formattedList = data.result.list.map(item => ({
            ...item,
            // 确保必要字段存在，避免undefined
            title: item.title || '无标题',
            src: item.src || '未知来源',
            time: item.time || new Date().toISOString(),
            content: item.content || '暂无内容'
          }));
          
          // 第一页直接赋值，后续页追加
          if (page === 1) {
            newsList.value = formattedList;
          } else {
            newsList.value = [...newsList.value, ...formattedList];
          }
          
          // 判断是否还有更多数据
          hasMore.value = page < Math.ceil(data.result.num / 10);
        } else {
          hasMore.value = false;
          errorMessage.value = data.msg || '数据格式不正确';
          console.error('API返回异常:', data);
        }
      } catch (error) {
        console.error('获取新闻失败:', error);
        errorMessage.value = '网络请求失败，请检查网络连接或接口地址';
      } finally {
        loading.value = false;
        isLoadingMore.value = false;
      }
    }
    
    // 图片加载失败处理
    function handleImageError(index) {
      console.log(`图片加载失败，索引: ${index}`);
      newsList.value[index].pic = ''; // 标记图片加载失败
    }
    
    // 加载更多
    function loadMore() {
      if (isLoadingMore.value || !hasMore.value) return;
      currentPage.value++;
      fetchNewsData(currentPage.value);
    }
    
    // 时间格式化
    function formatTime(timeStr) {
      if (!timeStr) return '';
      try {
        const date = new Date(timeStr);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        console.error('时间格式化失败:', timeStr, error);
        return timeStr;
      }
    }
    
    // 内容截断
    function truncateContent(content) {
      // 简单截断HTML内容，保留前100个非HTML字符
      const text = content.replace(/<[^>]+>/g, '').trim();
      return text.length > 100 ? text.substring(0, 100) + '...' : text;
    }
    
    // 跳转到详情页
    function goToDetail(url) {
      console.log('查看详情:', url);
      if (url) window.open(url, '_blank');
    }
    
    // 监听滚动加载更多
    function handleScroll() {
      if (isLoadingMore.value || !hasMore.value) return;
      
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
      if (scrollTop + clientHeight >= scrollHeight - 100) { // 距离底部100px时加载
        loadMore();
      }
    }
    
    // 生命周期钩子
    onMounted(() => {
      console.log('组件挂载，开始获取新闻数据');
      fetchNewsData();
      window.addEventListener('scroll', handleScroll);
    });
    
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });
    
    return {
      newsList,
      loading,
      errorMessage,
      hasMore,
      isLoadingMore,
      formatTime,
      goToDetail,
      loadMore,
      truncateContent
    };
  }
};
</script>

<style scoped>
/* 基础样式 */
.news-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 15px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/* 页面头部 */
.page-header {
  margin-bottom: 20px;
  text-align: center;
}
.page-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #999;
}
.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(99, 102, 241, 0.3);
  border-radius: 50%;
  border-top-color: #6366f1;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 15px;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 错误提示 */
.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #f56c6c;
  text-align: center;
}
.icon-error {
  font-size: 60px;
  margin-bottom: 15px;
}

/* 新闻列表样式 */
.news-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.news-item {
  display: flex;
  padding: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}
.news-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 图片样式 */
.news-image {
  position: relative;
  width: 100px;
  height: 100px;
  margin-right: 15px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
  background-color: #f5f5f5;
}
.image-item {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}
.news-item:hover .image-item {
  transform: scale(1.05);
}
.no-image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 12px;
  color: #999;
}

/* 内容样式 */
.news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.news-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.news-desc {
  font-size: 0.9rem;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 元信息样式 */
.news-meta {
  display: flex;
  align-items: center;
  font-size: 0.8rem;
  color: #999;
}
.source, .time, .category {
  margin-right: 15px;
  display: flex;
  align-items: center;
}
.source::before, .category::before {
  content: '';
  display: inline-block;
  width: 1px;
  height: 12px;
  background-color: #ddd;
  margin-right: 8px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #999;
  text-align: center;
}
.icon-empty {
  font-size: 80px;
  margin-bottom: 20px;
}

/* 分页控件 */
.pagination {
  margin: 30px 0;
  padding: 12px 0;
  text-align: center;
  color: #6366f1;
  border-top: 1px solid #eee;
  cursor: pointer;
  font-weight: 500;
}
</style>